import axios from 'axios'
import qs from 'qs'
// import Vue from 'vue'
// import store from '@/store/index'
// import vuex from 'vuex'
import router from "../router/index"
import {Toast} from "vant";
// console.log(...vuex.mapMutations)
axios.defaults.timeout = 20000; // 请求超时时间
axios.defaults.baseURL = process.env.VUE_APP_BASE_API;
axios.defaults.headers.post['Content-Type'] =
    'application/x-www-form-urlencoded;charset=UTF-8'; // post请求头的设置
// axios.defaults.headers.common["token"] = getCookie("token") ? getCookie("token") : ""
// axios respone拦截器
axios.defaults.headers.common["client_id"]="webApp";
axios.defaults.headers.common["client_secret"]="webApp";
axios.defaults.headers.common["system_id"]="wscc";

// "client_id":"webApp",
// "client_secret":"webApp",
var loading;
axios.interceptors.request.use(config => {

    config.headers.Authorization = "";
    if (sessionStorage.getItem("token")) {

        config.headers.Authorization = "Bearer " + sessionStorage.getItem("token");
    }
    if(sessionStorage.getItem("web_version")){
        config.headers.web_version =sessionStorage.getItem("web_version");
    }
    loading = Toast.loading({
        message: '加载中...',
        forbidClick: true,
    });
    if(config.params){

        if(config.params.hasOwnProperty("overTime")){
            axios.defaults.timeout = 600000
        }else{
            axios.defaults.timeout = 20000
        }
    }



    return config;
},error => {
    loading.clear();
    return Promise.reject(err)
});
var noError=true;
var timo=null;
axios.interceptors.response.use( response => {

    loading.clear();
    if (response.status === 200) {
        return Promise.resolve(response)
    }
    else {

        Toast({type:"fail",message:response.data.msg,duration:5000});

        return Promise.reject(response)
    }
}, err => {


    if (err && err.response) {
        loading.clear();
        console.log(err.response)
        switch (err.response.status) {
         
            case 400: err.message = err.response ? err.response.data.msg:'请求错误(400)' ; break;
            case 401: err.message =  err.response ? err.response.data.msg:'未授权，请重新登录(401)'; break;
            case 403: err.message =  err.response ? (err.response.data.msg||'拒绝访问(403)'):'拒绝访问(403)'; break;
            case 404: err.message = '请求出错(404)'; break;
            case 408: err.message = '请求超时(408)'; break;
            case 500: err.message = err.response ? (err.response.data.msg || "服务器错误(500)") : "服务器错误(500)"; break;
            case 501: err.message = '服务未实现(501)'; break;
            case 502: err.message = '网络错误(502)'; break;
            case 503: err.message = '服务不可用(503)'; break;
            case 504: err.message = '网络超时(504)'; break;
            case 505: err.message = 'HTTP版本不受支持(505)'; break;
            default: err.message = `连接出错(${err.response.status})!`;

        }
        if(err.response.status=="401"){
            noError=true;
            // sessionStorage.removeItem("token");
            // sessionStorage.removeItem("isLogin");
                    // router.push("/login");
        }
    }else{
        err.message = '连接服务器失败!'
    }
    if(err.response.status=='401'){
        sessionStorage.clear();
        router.push('/login');
        if(noError){
            Toast({type:"fail",message:err.message,duration:5000});
            noError=false;
        }else {
            clearTimeout(timo);
            timo=setTimeout( ()=> {
                noError=true
            },2000)
        }

    }else{
        Toast({type:"fail",message:err.message,duration:5000});
    }
   


    return Promise.reject(err);
});
// var needRequestCount=1;
function hideScreenLoading(){
    // if(needRequestCount<=0)  return
    // needRequestCount--;
    // needRequestCount = Math.max(needRequestCount, 0);
    // if(needRequestCount===0){
    loading.clear();
    // }
}
/**
 * 封装get方法，对应get请求
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 */
function get(url, params = {}, headers) {
    // if (headers && headers['client_id']) {
    //     axios.defaults.headers.common["client_id"]=headers['client_id'];
    // } else {
    //     axios.defaults.headers.common["client_id"]='webApp';
    // }
    // if (headers && headers['client_secret']) {
    //     axios.defaults.headers.common["client_secret"]=headers['client_secret'];
    // } else {
    //     axios.defaults.headers.common["client_secret"]='webApp';
    // }
    return new Promise((resolve, reject) => {
        axios
            .get(url, {
                params: params
            })
            .then(res => {
                resolve(res)
            })
            .catch(err => {
                reject(err)
            })
    })
    // 或者return axios.get();
}
/**
 * form方法，对应post请求
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 */
function form(url, params) {
    return new Promise((resolve, reject) => {
        axios
            .post(url, qs.stringify(params))
            .then(res => {
                resolve(res);
            })
            .catch(err => {
                reject(err)
            })
    })
    //  或者return axios.post();
}

/**
 * post方法，对应post请求
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 */
function post(url, postData, query = {}) {
    if(query["content-type"]){
        return new Promise((resolve, reject) => {
            // 创建form对象
           // 通过append向form对象添加数据
            let params = new FormData();
            for(let i in postData){

                console.log(postData[i])
                params.append(i, postData[i]);
            }
            axios.post(url, params,{
                headers:{
                    "Content-Type":query["content-type"]
                }
            }) .then(res => {
                resolve(res);
            }).catch(err => {
                reject(err)
            });
        })
    }else{
        return new Promise((resolve, reject) => {
            axios.post(url, postData) .then(res => {
                resolve(res);
            }).catch(err => {
                reject(err)
            });
        })
    }

    // return post;
}

/**
 * delete方法，对应put请求
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 */
function Delete(url, params) {
    return new Promise((resolve, reject) => {
        axios
            .delete(url, {data:params})
            .then(res => {
                resolve(res)
            })
            .catch(err => {
                reject(err)
            })
    })
    //  或者return axios.post();
}

/**
 * delete方法，对应put请求
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 */
function del(url, params) {
    // let param = new FormData();
    // for(let i in params){
    //     param.append(i, params[i]);
    // }
    return new Promise((resolve, reject) => {
        axios
            .delete(url, {data:params})
            .then(res => {
                resolve(res)
            })
            .catch(err => {
                reject(err)
            })
    })
    //  或者return axios.post();
}

/**
 * delete方法，对应put请求
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 */
function put(url, params) {
    return new Promise((resolve, reject) => {
        axios
            .put(url, params)
            .then(res => {
                resolve(res)
            })
            .catch(err => {
                reject(err)
            })
    })
    //  或者return axios.post();
}
export {
    get,
    post,
    form,
    Delete,
    put,
    del,

}